#!C:\python25\python.exe
# -*- coding: UTF-8 -*-

"""
1.一个后台进程中创建两个服务器,分别监听79和1079端口
2.端口79用于回显客户端的输入
3.端口1079用于在服务器端显示客户端的输入
"""
from twisted.application import internet,service
from twisted.internet import protocol,reactor,defer
from twisted.protocols import basic
# 用于回显客户端的数据
class FingerProtocol(basic.LineReceiver):
    def lineReceived(self,user):
        self.factory.getUser(user,
        ).addErrback(lambda _:"internal error in server"
        ).addCallback(lambda m:(self.transport.write(m + "\r\n"),
                                self.transport.loseConnection())
        )
class FingerFactory(protocol.ServerFactory):
    protocol = FingerProtocol
    def __init__(self,**kwargs):self.users = kwargs
    def getUser(self,user):
        return defer.succeed(self.users.get(user,"No such user"))
# 用于在服务器端显示客户端的数据
class FingerSetterProtocol(basic.LineReceiver):
    def connectionMade(self):self.lines = []
    def lineReceived(self,line):
        self.lines.append(line)
        print(line)
    def connectionLost(self,reason):
        self.factory.setUser(*self.lines[:2])
class FingerSetterFactory(protocol.ServerFactory):
    protocol = FingerSetterProtocol
    def __init__(self,ff):self.setUser = ff.users.__setitem__

ff = FingerFactory(jcodeer = "jcodeer.cublog.cn")
fsf = FingerSetterFactory(ff)
application = service.Application("finger")
serviceCollection = service.IServiceCollection(application)
# 创建两个服务器
internet.TCPServer(79,ff).setServiceParent(serviceCollection)
internet.TCPServer(1079,fsf).setServiceParent(serviceCollection)
